package cn.edu.imau.zy.activiti.service.impl;

import cn.edu.imau.zy.activiti.domain.BizAudit;
import cn.edu.imau.zy.activiti.service.IAuditExtendService;
import cn.edu.imau.zy.activiti.service.IBizAuditService;
import cn.edu.imau.zy.activiti.service.IBizBusinessService;
import cn.edu.imau.zy.activiti.vo.HiTaskVo;
import cn.edu.imau.zy.common.constant.ActivitiConstant;
import cn.edu.imau.zy.common.constant.DictConstant;
import cn.edu.imau.zy.common.core.entity.activiti.BizBusiness;
import cn.edu.imau.zy.common.core.entity.student.StLeave;
import cn.edu.imau.zy.common.core.entity.student.StStudentPoor;
import cn.edu.imau.zy.common.core.entity.system.SysUser;
import cn.edu.imau.zy.common.utils.StringUtils;
import cn.edu.imau.zy.system.feign.RemoteStudentPoorService;
import cn.edu.imau.zy.system.weChat.WeChatApi;
import cn.edu.imau.zy.system.feign.RemoteStudentLeaveService;
import cn.edu.imau.zy.system.feign.RemoteUserService;
import lombok.Data;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: xsc-cloud
 * @description: 审批扩展业务实现
 * @author: Wuyz
 * @create: 2020-11-20 18:03
 **/
@Service
public class AuditExtendServiceImpl implements IAuditExtendService {

    private static final Logger log = LoggerFactory.getLogger(AuditExtendServiceImpl.class);

    @Autowired
    private TaskService taskService;
    @Autowired
    private RemoteStudentLeaveService remoteStudentLeaveService;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private WeChatApi weChatApi;
    @Autowired
    private IBizBusinessService bizBusinessService;
    @Autowired
    private IBizAuditService auditService;
    @Autowired
    private RemoteStudentPoorService studentPoorService;

    @Override
    public void extend(BizAudit bizAudit, BizBusiness business) {
        if (bizAudit.getProcDefKey().equals(ActivitiConstant.ACT_TYPE_LEAVE)) {
            Task task = taskService.createTaskQuery().taskId(bizAudit.getTaskId()).singleResult();
            StLeave leave = new StLeave();
            leave.setId(business.getTableId());
            if ("leave_leader_ap".equals(task.getTaskDefinitionKey()) || "leave_act_step_1".equals(task.getTaskDefinitionKey())) {
                //班主任第一次审批 有参数需要保存
                leave.setVerify((boolean) bizAudit.getParams().get("verify"));
                leave.setAgree((boolean) bizAudit.getParams().get("agree"));
                leave.setRecordPicture(bizAudit.getParams().get("recordPicture").toString());

                System.out.println("<----------------------------------------->");
                System.out.println(leave);
                System.out.println("<----------------------------------------->");

                StLeave leaveTmp = remoteStudentLeaveService.getById(business.getTableId());

                System.out.println("-----------------------------------------");
                System.out.println("leaveTmp:" + leaveTmp );
                System.out.println("-----------------------------------------");

                if (!leaveTmp.getEgress() && bizAudit.getResult().equals(ActivitiConstant.RESULT_PASS)) {
                    leave.setStatus(ActivitiConstant.STATUS_FINISH.toString());
                }

                System.out.println("-----------------------------------------");
                System.out.println("leave:"+leave);
                System.out.println("-----------------------------------------");

                remoteStudentLeaveService.editSave(leave);

            } else if ("leave_act_step_5".equals(task.getTaskDefinitionKey()) && bizAudit.getResult().equals(ActivitiConstant.RESULT_PASS)) {
                // 分管院长审批通过,需要变更状态
                leave.setStatus(ActivitiConstant.STATUS_FINISH.toString());
                remoteStudentLeaveService.editSave(leave);
            } else if ("leave_act_step_6".equals(task.getTaskDefinitionKey())) {
                // 学生销假申请
                leave.setReleaveAddress(bizAudit.getParams().get("releaveAddress").toString());
                remoteStudentLeaveService.editSave(leave);
            } else if ("leave_act_step_7".equals(task.getTaskDefinitionKey())) {
                // 班主任审批销假
                leave.setReleave(true);
                leave.setReleaveTime(LocalDateTime.now());
                leave.setResult(ActivitiConstant.RESULT_PASS.toString());
                remoteStudentLeaveService.editSave(leave);
            }
            if (bizAudit.getResult().equals(ActivitiConstant.RESULT_FAIL)) {
                //任何一步拒绝 均需要改变状态
                leave.setStatus(ActivitiConstant.STATUS_FINISH.toString());
                leave.setResult(ActivitiConstant.RESULT_FAIL.toString());
                remoteStudentLeaveService.editSave(leave);
            }
        } else if (bizAudit.getProcDefKey().equals(ActivitiConstant.ACT_TYPE_RELEAVE)) {
            Task task = taskService.createTaskQuery().taskId(bizAudit.getTaskId()).singleResult();
            if ("releave_ap".equals(task.getTaskDefinitionKey())) {
                StLeave leave = new StLeave();
                leave.setId(business.getTableId());
                leave.setReleave(true);
                remoteStudentLeaveService.editSave(leave);
            }
        }
    }

    @Override
    public void sendMessage(String businessId) {
        BizBusiness business = bizBusinessService.selectBizBusinessById(businessId);
        if (ActivitiConstant.ACT_TYPE_LEAVE.equals(business.getProcDefKey())) {
            if (ActivitiConstant.STATUS_DEALING.equals(business.getStatus()) && ActivitiConstant.RESULT_DEALING.equals(business.getResult())) {
                log.info("处理中的流程，准备给下一审批人发送消息");
                List<Task> tasks = taskService.createTaskQuery().processInstanceId(business.getProcInstId()).list();
                if (null != tasks && tasks.size() > 0) {
                    Task task = tasks.get(0);
                    if ("leave_act_step_6".equals(task.getTaskDefinitionKey())) {
                        // 待销假节点---请假成功
                        SysUser user = remoteUserService.selectSysUserByUserId(business.getUserId());
                        if (user == null || StringUtils.isEmpty(user.getOpenId())) {
                            log.info("用户{}未绑定微信，无法推送订阅消息", user.getLoginName());
                            return;
                        }
                        Map<String, Object> data = new HashMap<>();
                        data.put("phrase1", new Value("通过"));
                        data.put("thing11", new Value(business.getApplyer()));
                        data.put("thing2", new Value(business.getTitle()));
                        data.put("date3", new Value(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"))));
                        data.put("thing7", new Value("请假申请通过,请返校后及时销假"));
                        Map<String, Object> params = new HashMap<>();
                        params.put("touser", user.getOpenId());
                        params.put("template_id", "Kk-i4pHD9m266dxTUAKy8EL4ejqy6JXM7lE7eslVx8c");
                        params.put("page", "/pages/login/login");
                        params.put("data", data);
                        weChatApi.subscribeMessageSend(params);
                    } else {
                        // 其他节点---待审批
                        List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(task.getId());
                        for (IdentityLink identityLink : identityLinks) {
                            SysUser user = remoteUserService.selectSysUserByUserId(identityLink.getUserId());
                            if (user == null || StringUtils.isEmpty(user.getOpenId())) {
                                log.info("用户{}未绑定微信，无法推送订阅消息", user.getLoginName());
                                return;
                            }
                            Map<String, Object> data = new HashMap<>();
                            data.put("thing2", new Value("请假审批"));
                            data.put("name1", new Value(business.getApplyer()));
                            data.put("time3", new Value(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"))));
                            data.put("thing4", new Value("请及时点击前往审批"));
                            Map<String, Object> params = new HashMap<>();
                            params.put("touser", user.getOpenId());
                            params.put("template_id", "lwR148NZAGrZ9O29t9Mv--FsHMRGMMvQ5qJNhYMQ4KM");
                            params.put("page", "/pages/login/login");
                            params.put("data", data);
                            weChatApi.subscribeMessageSend(params);
                        }
                    }

                }
            } else if (ActivitiConstant.STATUS_FINISH.equals(business.getStatus()) && ActivitiConstant.RESULT_PASS.equals(business.getResult())) {
                log.info("通过的流程，只给请假人发送信息");
                SysUser user = remoteUserService.selectSysUserByUserId(business.getUserId());
                if (user == null || StringUtils.isEmpty(user.getOpenId())) {
                    log.info("用户{}未绑定微信，无法推送订阅消息", user.getLoginName());
                    return;
                }
                Map<String, Object> data = new HashMap<>();
                data.put("phrase1", new Value("通过"));
                data.put("thing11", new Value(business.getApplyer()));
                data.put("thing2", new Value(business.getTitle()));
                data.put("date3", new Value(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"))));
                data.put("thing7", new Value("销假成功！"));
                Map<String, Object> params = new HashMap<>();
                params.put("touser", user.getOpenId());
                params.put("template_id", "Kk-i4pHD9m266dxTUAKy8EL4ejqy6JXM7lE7eslVx8c");
                params.put("page", "/pages/login/login");
                params.put("data", data);
                weChatApi.subscribeMessageSend(params);
            } else if (ActivitiConstant.STATUS_FINISH.equals(business.getStatus()) && ActivitiConstant.RESULT_FAIL.equals(business.getResult())) {
                // 驳回
                log.info("驳回的流程，给所有审批人和请假人发送驳回信息");
                HiTaskVo hiTaskParams = new HiTaskVo();
                hiTaskParams.setProcInstId(business.getProcInstId());
                List<HiTaskVo> hiTaskVos = auditService.getHistoryTaskList(hiTaskParams);
                HiTaskVo backInfo = new HiTaskVo();
                for (HiTaskVo hiTaskVo : hiTaskVos) {
                    if (hiTaskVo.getResult().equals(ActivitiConstant.RESULT_FAIL)) {
                        backInfo = hiTaskVo;
                        break;
                    }
                }
                Map<String, Object> data = new HashMap<>();
                data.put("phrase1", new Value("不通过"));
                data.put("thing11", new Value(business.getApplyer()));
                data.put("thing2", new Value(business.getTitle()));
                data.put("date3", new Value(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"))));
                data.put("thing7", new Value(backInfo.getComment()));
                Map<String, Object> params = new HashMap<>();
                params.put("template_id", "Kk-i4pHD9m266dxTUAKy8EL4ejqy6JXM7lE7eslVx8c");
                params.put("page", "/pages/login/login");
                params.put("data", data);
                for (HiTaskVo hiTaskVo : hiTaskVos) {
                    if (hiTaskVo.getResult().equals(ActivitiConstant.RESULT_PASS)) {
                        SysUser user = remoteUserService.selectSysUserByUserId(hiTaskVo.getAuditorId());
                        if (user == null || StringUtils.isEmpty(user.getOpenId())) {
                            log.info("用户{}未绑定微信，无法推送订阅消息", user.getLoginName());
                            continue;
                        }
                        params.put("touser", user.getOpenId());
                        weChatApi.subscribeMessageSend(params);
                    }
                }
                SysUser user = remoteUserService.selectSysUserByUserId(business.getUserId());
                if (user == null || StringUtils.isEmpty(user.getOpenId())) {
                    log.info("用户{}未绑定微信，无法推送订阅消息", user.getLoginName());
                    return;
                }
                params.put("touser", user.getOpenId());
                weChatApi.subscribeMessageSend(params);
            }
        }
    }

    @Override
    public void cancel(BizBusiness bb) {
        if (bb.getProcDefKey().equals(ActivitiConstant.ACT_TYPE_POOR)) {
            StStudentPoor studentPoor = new StStudentPoor();
            studentPoor.setId(bb.getTableId());
            studentPoor.setStatus(DictConstant.POOR_STATUS.DEFAULT);
            studentPoorService.editSave(studentPoor);
        } else if (bb.getProcDefKey().equals(ActivitiConstant.ACT_TYPE_LEAVE)) {
            StLeave leave = new StLeave();
            leave.setId(bb.getTableId());
            leave.setStatus(ActivitiConstant.STATUS_CANCELED.toString());
            leave.setResult(ActivitiConstant.RESULT_CANCELED.toString());
            remoteStudentLeaveService.editSave(leave);
        }
    }

    @Data
    class Value {
        public Value(String value) {
            this.value = value;
        }

        private String value;

        @Override
        public String toString() {
            return "{\"value\":\"" + this.value + "\"}";
        }
    }
}
